package data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Conexion {
    private Connection conn = null;
    private Statement stmt = null;
    private ResultSet rs = null;
    
    private final String url = "jdbc:sqlserver://localhost:1433"; // <ip> y <puerto> servidor
    private final String model = "baedynamics"; //base de datos  --->>> cambiar nombre
    private final String usuario = "sa"; //usuario
    private final String password = "1234"; //contraseña

    public Conexion() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
        }

        try {
            conn = DriverManager.getConnection(url+";databaseName="+model+
                    ";user="+usuario+";password="+password+";");

        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
    }

    public PreparedStatement getPreparedStatement(String sql) {
        try {
            return conn.prepareStatement(sql);
        } catch (SQLException e) {
        }
        return null;
    }

    public ResultSet executeQuery(String sql) {
        try {
            stmt = conn.createStatement();
            return stmt.executeQuery(sql);
        } catch (SQLException e) {
        }
        return null;
    }

    public void cerrar() {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException sqlEx) {
            } // ignore
            rs = null;
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException sqlEx) {
            } // ignore
            stmt = null;
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException sqlEx) {
            } // ignore
            conn = null;
        }
    }
}
